package com.knowif.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.knowif.dao.RedpacketActivityMapper;
import com.knowif.enumInfo.RedPacketEnum;
import com.knowif.enumInfo.UserShareEnum;
import com.knowif.pojo.RedpacketActivity;
import com.knowif.pojo.RedpacketActivityExample;
import com.knowif.pojo.TUser;
import com.knowif.pojo.UserRedpacket;
import com.knowif.pojo.UserRedpacketExample;
import com.knowif.pojo.UserShare;
import com.knowif.system.model.RestBean;
import com.knowif.util.commonUtil.DateUtils;
import com.knowif.util.commonUtil.IntegerUtil;
import com.knowif.util.commonUtil.SetUtil;

/**
 * @author xingyao
 * @Description: 红包管理dao服务层
 */
@Service
public class Redpacket_service {
	
	
	@Autowired
	private RedpacketActivityMapper redpacketActivityMapper;
	
	@Autowired
	private UserRedpacket_Service userRedpacket_Service;
	
	
	@Autowired
	private UserShare_service userShare_service;
	
//	@Autowired
//	private TUserMapper tUserMapper;
	
	
	@Autowired
	private User_service user_service;
	
	/**
	 * @author: xingyao 
	 * @Description:  创建红包活动信息表
	 * @param redpacketActivity
	 * @return
	 */
	public RestBean<?> createRedPacketActivity(RedpacketActivity redpacketActivity){
		int id = redpacketActivityMapper.insert(redpacketActivity);
		redpacketActivity.setId(id);
		return RestBean.buildSuccess(redpacketActivity);
	}
	
	/**
	 * @author: xingyao 
	 * @Description:  
	 * 				创建用户分享红包,先进行查询，如果查询出来有统一活动的分享，则不需要做操作，没有则需要做插入操作
	 * 				如果没有查询到分享活动，则需要先通过activityId进行活动查询，如果存在活动，并且活动没有过期，则进行活动创建
	 * @param userRedpacket
	 * @return
	 * @throws Exception 
	 */
	public RestBean<?> createUserRedPacket(UserRedpacket userRedpacket) throws Exception{
		List<UserRedpacket> userRedpackets = userRedpacket_Service.selectByUserIdAndActivityId(userRedpacket.getUserId(),userRedpacket.getActivityId());
		RedpacketActivity redpacketActivity = selectById(userRedpacket.getActivityId());
		Integer id = null;
		if(userRedpackets == null || userRedpackets.isEmpty()){
			
			if(redpacketActivity == null){
				return RestBean.buildError("不存在这项活动");
			}else if(DateUtils.date1MothanDate2(new Date(), redpacketActivity.getEndTime())){
				return RestBean.buildError("红包活动已经过期");
			}else if(DateUtils.date1MothanDate2(redpacketActivity.getBeginTime(), new Date())){
				return RestBean.buildError("红包活动还没有开始，不能进行创建");
			}
			userRedpacket.setBeginTime(redpacketActivity.getBeginTime());
			userRedpacket.setEndTime(redpacketActivity.getEndTime());
			userRedpacket.setUsedTime(redpacketActivity.getUsedTime());
			userRedpacket.setStatus(RedPacketEnum.OK.getStatus());
			id = userRedpacket_Service.insert(userRedpacket);
			userRedpacket.setId(id);
			userRedpacket.setRedpacketActivity(redpacketActivity);
			//返回创建成果的分享
			return RestBean.buildSuccess(userRedpacket);
		}else{
			//如果当前时间超过了最后使用时间，那么这个红包就是过期的，那么就应该更新状态
			if(DateUtils.date1MothanDate2(new Date(), userRedpacket.getEndTime())){
				userRedpacket.setStatus(RedPacketEnum.PASTTIME.getStatus());
				userRedpacket_Service.updateById(userRedpacket);
				return RestBean.buildError("红包活动已经过期");
				//如果开始时间大于现在的时间，说明活动还没有开始，不能进行创建分享
			}else if(DateUtils.date1MothanDate2(userRedpacket.getBeginTime(), new Date())){
				return RestBean.buildError("红包活动还没有开始，不能进行创建");
			}else{
				userRedpackets.get(0).setRedpacketActivity(redpacketActivity);
				return RestBean.buildSuccess(userRedpackets.get(0));
			}
		}
	}

	public RedpacketActivity selectById(Integer activityId) {
		if(IntegerUtil.isEmpty(activityId)){
			return null;
		}
		RedpacketActivity redpacketActivity = redpacketActivityMapper.selectByPrimaryKey(activityId);
		return redpacketActivity;
	}


	/**
	 * @author: xingyao 
	 * @Description:  获取所有的红包活动信息,默认是查找没有过期的
	 * @param activityId
	 * @return
	 */
	public RestBean<?> selectActivity(RedpacketActivityExample redpacketActivityExample){
		if(redpacketActivityExample == null){
			redpacketActivityExample = new RedpacketActivityExample();
			redpacketActivityExample.createCriteria().andEndTimeGreaterThanOrEqualTo(new Date());
		}
		List<RedpacketActivity> redpacketActivities = redpacketActivityMapper.selectByExample(redpacketActivityExample);
		return RestBean.buildSuccess(redpacketActivities);
	}
	
	/**
	 * @author: xingyao 
	 * @Description:  添加用户分享后的记录
	 * 			前置：通过userShare的user_redpacket_id查找user_redpacket表，得到信息。
	 * 			1、通过user_redPacket_id查找到对应的用户红包活动记录，查找到shared_num和acticity_id
	 * 			2、通过acticity_id查找redpacket_activity表，找到对应的share_num
	 * 			3、判断shared_num<share_num
	 * 				3.1、如果是，则进行插入操作。再插入操作进行的时候，还要通过shared_num字段进行更新，也就是说如果shared_num=1，则更新条件是where shared_num = 1,
	 * 				防止在执行更新操作的时候，另一个人也执行了更新操作。如果执行更新条件数量为0，则需要再执行一遍3。直到最后更新成功或者shared_num>share_num(更新失败)
	 * 				3.2、如果否，直接更新失败
	 *			4、插入一条记录到user_share表中
	 * @param user_redPacket_id
	 * @param user_id
	 * @return
	 */
	@Transactional
	public RestBean<?> saveUserShare(UserShare userShare){
		if(userShare == null){
			return RestBean.buildError("用户分享信息不能为空");
		}
		UserRedpacket userRedpacket = userRedpacket_Service.selectById(userShare.getUserRedpacketId());
		RedpacketActivity redpacketActivity = selectById(userRedpacket.getActivityId());
		if(redpacketActivity == null){
			return RestBean.buildError("不存在这项活动");
		}else if(DateUtils.date1MothanDate2(new Date(), redpacketActivity.getEndTime())){
			return RestBean.buildError("红包活动已经过期");
		}else if(DateUtils.date1MothanDate2(redpacketActivity.getBeginTime(), new Date())){
			return RestBean.buildError("红包活动还没有开始，不能进行创建");
		}
		int whileNum = 0;
		//原则上是会调出循环的，后面加个whileNum > redpacketActivity.getShareNum()，是为了怕系统出错，在这里无线循环。
		//所以设置最高的循环次数为分享人随的最高次数，这样就不怕无线循环
		while(true && (whileNum > redpacketActivity.getShareNum())){
			userRedpacket = userRedpacket_Service.selectById(userShare.getUserRedpacketId());
			//如果已经分享的用户大于等于(逻辑上只有等于)
			if(userRedpacket.getSharedNum()==redpacketActivity.getShareNum()){
				return RestBean.buildError("红包已经帮领完了");
			}
			if(userRedpacket.getSharedNum()>redpacketActivity.getShareNum()){
				//这里应该发出警告，因为实际分享人数超过了系统设置的
				return RestBean.buildError("系统出错，请稍后再试");
			}
			double money = redpacketActivity.getAmount() - userRedpacket.getSharedAmount();
			double shareAmount = 0;
			//判断是否只剩下最后一个分享名额，如果是，则需要将剩余的所有金额给这个分享名额
			if(userRedpacket.getSharedNum()+1 ==redpacketActivity.getShareNum() ){
				shareAmount = money;
			}else{
				//在0.01到剩余金额中产生一个随机金额
				shareAmount =new Random().nextDouble() * (money-0.01)+0.01;
			}
			userRedpacket.setSharedAmount((userRedpacket.getSharedAmount()+shareAmount));
			userRedpacket.setSharedNum(userRedpacket.getSharedNum()+1);
			int result = userRedpacket_Service.update(userRedpacket.getSharedNum(), userRedpacket.getActivityId(), userRedpacket.getUserId(), userRedpacket);
			if(result == 1){
				//说明在这只见没有人进行更新，可以尽享分享
				userShare.setShareMoney(shareAmount); 
				userShare.setStatus(UserShareEnum.SUCCESS.getNumber());
				userShare_service.insert(userShare);
				//调出循环
				return RestBean.build(RestBean.success_code, "分享成功", userShare);
			}
		}
		return RestBean.buildError("分享失败");
	}
	
	/**
	 * @author: xingyao 
	 * @Description:  查找用户创建的红包分享
	 * @param userRedpacketExample
	 * @return
	 */
	public RestBean<?> selectAllUserRedpacket(UserRedpacketExample redpacketExample){
		List<UserRedpacket> userRedPackets = userRedpacket_Service.selectByExample(redpacketExample);
		if(userRedPackets == null || userRedPackets.isEmpty()){
			return RestBean.build(RestBean.success_code,"没有用户分享的红包的数据",userRedPackets);
		}
		Set<Integer> activityIds = UserRedpacket.getActivityIds(userRedPackets);
		List<RedpacketActivity> redpacketActivities = selectByActivityIds(SetUtil.set2List4Int(activityIds));
		UserRedpacket.saveRedpacketActivity(userRedPackets, redpacketActivities);
		Set<Integer> userIds = UserRedpacket.getUserIds(userRedPackets);
		
		List<TUser> tUsers =  user_service.selectByUserIds(SetUtil.set2List4Int(userIds));
		
		UserRedpacket.saveTuser(userRedPackets, tUsers);
		return RestBean.buildSuccess(userRedPackets);
	}



	public List<RedpacketActivity> selectByActivityIds(List<Integer> activityIds) {
		if(activityIds == null || activityIds.isEmpty()){
			return new ArrayList<RedpacketActivity>();
		}
		RedpacketActivityExample redpacketActivityExample = new RedpacketActivityExample();
		redpacketActivityExample.createCriteria().andIdIn(activityIds);
		List<RedpacketActivity> redpacketActivities = redpacketActivityMapper.selectByExample(redpacketActivityExample);
		return redpacketActivities;
	}
	
	/**
	 * @author: xingyao 
	 * @Description:  得到用户分享信息
	 * @param userShareExample
	 * @return
	 */
	public RestBean<?> getRedShare(Integer userRedpacketId){
		if(userRedpacketId == null || userRedpacketId == 0){
			return RestBean.buildError("userRedpacketId不能为空");
		}
		
		
		List<UserShare> userShares = userShare_service.selectByUserRedpacketId(userRedpacketId);
		Set<Integer> ownerIds = UserShare.getOwnerIds(userShares);
		List<TUser> owners = user_service.selectByUserIdsAndNotDelete(SetUtil.set2List4Int(ownerIds));
		UserShare.saveOwner(userShares, owners);
		
		Set<Integer> sharerids = UserShare.getShareIds(userShares);
		List<TUser> sharers = user_service.selectByUserIdsAndNotDelete(SetUtil.set2List4Int(sharerids)); 
		UserShare.saveShare(userShares, sharers);
		UserRedpacket userRedpacket = userRedpacket_Service.selectById(userRedpacketId);
		for(UserShare userShare : userShares){
			userShare.setUserRedpacket(userRedpacket);
		}
		return RestBean.buildSuccess(userShares);
	}

	

	


}












